import requests
import json
import random
from utils.usually_data import USER_AGENTS
from setting import *
from utils.proxy import get_proxy
import lxml.html

def get_city():
    url = city_url
    html_info = requests.get(url)
    html = lxml.html.etree.HTML(html_info.text)  # 初始化生成一个XPath解析对象
    items = html.xpath('//div[@class="all"]//a/text()')
    return items


def get_city_data():
    url = city_url
    html_info = requests.get(url)
    result = []
    html = lxml.html.etree.HTML(html_info.text)  # 初始化生成一个XPath解析对象
    items = html.xpath('//div[@class="all"]//ul[@class="unstyled"]')
    for i in items:
        cityName = i.xpath('div/li/a/text()')
        first_letter = i.xpath('div/b/text()')
        for c in cityName:
            result.append([c, first_letter[0][:-1]])
    for k, v in enumerate(result):
        result[k].append(k)
    return result

# 解码response对象
def decode_info(info, ctx):
    js = 'decodeData("{0}")'.format(info)
    data = ctx.eval(js)
    data = json.loads(data)
    return data


def get_response(params):
    url = data_url
    data = {
        'hd': params
    }
    # 动态代理
    if useProxy:
        headers, proxies = get_proxy()
    else:
        headers, proxies = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.8',
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': random.choice(USER_AGENTS)
        }, {}
    html_info = requests.post(url, data=data, headers=headers, proxies=proxies)
    if html_info.status_code is 200:
        return html_info.text
    else:
        return None


def day_params(city, date_time, ctx):
    method = 'GETDAYDATA'
    js = 'getEncryptedData("{0}", "{1}", "{2}")'.format(method, city, date_time)
    return ctx.eval(js)


def month_params(city, date_time, ctx):
    method = 'GETMONTHDATA'
    js = 'getEncryptedData("{0}", "{1}", "{2}")'.format(method, city, date_time)
    return ctx.eval(js)


def en_day_sdict_to_list(cityName, result):
    return [cityName, result['time_point'], result['aqi'], result['pm2_5'], result['pm10'], result['so2'],
            result['no2'], result['co'], result['o3'],
            result['rank'], result['quality']]


def en_month_dict_to_list(cityName, result):
    return [cityName, result['time_point'], result['aqi'], result['max_aqi'], result['min_aqi'], result['pm2_5'],
            result['pm10'], result['so2'],
            result['no2'], result['co'], result['o3'],
            result['rank'], result['quality']]